package com.lt.common;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

import com.lt.LibConstant;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.util.HashMap;

public class ConvertHelper
{

    private static ConvertHelper instance;
    public static final int KB = 1024;

    private ConvertHelper()
    {
    }

    public static ConvertHelper getInstance()
    {
        if (instance == null)
        {
            synchronized (ConvertHelper.class)
            {
                instance = new ConvertHelper();
            }
        }
        return instance;
    }

    public String getStr(Object o, String defaultValue)
    {
        String re = defaultValue;
        if (o != null)
        {
            re = String.valueOf(o);
        }
        return re;
    }

    public String getStr(Object o)
    {
        return getStr(o, "");
    }

    public int getInt(Object o, int defaultValue)
    {
        int re = defaultValue;
        if (o instanceof Float)
        {
            re = Math.round((Float) o);
        } else if (o instanceof Double)
        {
            re = (int) Math.round((Double) o);
        } else if (o != null)
        {
            try
            {
                re = Integer.parseInt(getStr(o));
            } catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        return re;
    }

    public int getInt(Object o)
    {
        return getInt(o, 0);
    }

    public float getFloat(Object o, float defaultValue)
    {
        float re = defaultValue;
        if (o instanceof Float)
        {
            re = Math.round((Float) o);
        } else if (o instanceof Double)
        {
            re = Math.round((Double) o);
        } else if (o != null)
        {
            try
            {
                re = Float.parseFloat(getStr(o));
            } catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        return re;
    }

    public float getFloat(Object o)
    {
        return getFloat(o, 0);
    }

    public boolean getBoolean(Object o, boolean defaultValue)
    {
        boolean re = defaultValue;
        if (o != null)
        {
            try
            {
                re = Boolean.parseBoolean(getStr(o));
            } catch (Exception e)
            {
                // TODO: handle exception
            }
            if (!re && getInt(o) == 1)
            {
                re = true;
            }
        }
        return re;
    }

    public boolean getBoolean(Object o)
    {
        return getBoolean(o, false);
    }

    public long getLong(Object o, long defaultValue)
    {
        long re = defaultValue;
        if (o != null)
        {
            try
            {
                re = Long.parseLong(getStr(o));
            } catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        return re;
    }

    public long getLong(Object o)
    {
        return getLong(o, 0);
    }

    public double getDouble(Object o, double defaultValue)
    {
        double re = defaultValue;
        if (o != null)
        {
            try
            {
                re = Double.parseDouble(getStr(o));
            } catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        return re;
    }

    public double getDouble(Object o)
    {
        return getDouble(o, 0);
    }

    /**
     * byteArr转hexString
     * <p>
     * 例如：
     * </p>
     * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8
     *
     * @param bytes 字节数组
     * @return 16进制大写字符串
     */
    public String bytes2HexString(byte[] bytes)
    {
        if (bytes == null)
            return null;
        int len = bytes.length;
        if (len <= 0)
            return null;
        char[] ret = new char[len << 1];
        for (int i = 0, j = 0; i < len; i++)
        {
            ret[j++] = LibConstant.DIGITS_UPPER[bytes[i] >>> 4 & 0x0f];
            ret[j++] = LibConstant.DIGITS_UPPER[bytes[i] & 0x0f];
        }
        return new String(ret);
    }

    /**
     * hexString转byteArr
     * <p>
     * 例如：
     * </p>
     * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }
     *
     * @param hexString 十六进制字符串
     * @return 字节数组
     */
    public byte[] hexString2Bytes(String hexString)
    {
        if (TextUtils.isEmpty(hexString))
            return null;
        int len = hexString.length();
        if (len % 2 != 0)
        {
            hexString = "0" + hexString;
            len = len + 1;
        }
        char[] hexBytes = hexString.toUpperCase().toCharArray();
        byte[] ret = new byte[len >> 1];
        for (int i = 0; i < len; i += 2)
        {
            ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
        }
        return ret;
    }

    /**
     * hexChar转int
     *
     * @param hexChar hex单个字节
     * @return 0..15
     */
    private int hex2Dec(char hexChar)
    {
        if (hexChar >= '0' && hexChar <= '9')
        {
            return hexChar - '0';
        } else if (hexChar >= 'A' && hexChar <= 'F')
        {
            return hexChar - 'A' + 10;
        } else
        {
            throw new IllegalArgumentException();
        }
    }

    /**
     * charArr转byteArr
     *
     * @param chars 字符数组
     * @return 字节数组
     */
    public byte[] chars2Bytes(char[] chars)
    {
        if (chars == null || chars.length <= 0)
            return null;
        int len = chars.length;
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++)
        {
            bytes[i] = (byte) (chars[i]);
        }
        return bytes;
    }

    public String fileToBase64(File file)
    {
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return null;
        }
        String base64String = null;
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1)
            {
                baos.write(buffer, 0, len);
            }
            byte[] fileBytes = baos.toByteArray();
            base64String = Base64.encodeToString(fileBytes, Base64.DEFAULT);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return base64String;
    }

    /**
     * byteArr转charArr
     *
     * @param bytes 字节数组
     * @return 字符数组
     */
    public char[] bytes2Chars(byte[] bytes)
    {
        if (bytes == null)
            return null;
        int len = bytes.length;
        if (len <= 0)
            return null;
        char[] chars = new char[len];
        for (int i = 0; i < len; i++)
        {
            chars[i] = (char) (bytes[i] & 0xff);
        }
        return chars;
    }

    /**
     * 以unit为单位的内存大小转字节数
     *
     * @param memorySize 大小
     * @param unit       单位类型
     *                   <ul>
     *                   <li>{@link LibConstant.MemoryUnit#BYTE}: 字节</li>
     *                   <li>{@link LibConstant.MemoryUnit#KB} : 千字节</li>
     *                   <li>{@link LibConstant.MemoryUnit#MB} : 兆</li>
     *                   <li>{@link LibConstant.MemoryUnit#GB} : GB</li>
     *                   </ul>
     * @return 字节数
     */
    public long memorySize2Byte(long memorySize, LibConstant.MemoryUnit unit)
    {
        if (memorySize < 0)
            return -1;
        switch (unit)
        {
            default:
            case BYTE:
                return memorySize;
            case KB:
                return memorySize * LibConstant.KB;
            case MB:
                return memorySize * LibConstant.MB;
            case GB:
                return memorySize * LibConstant.GB;
        }
    }

    /**
     * 字节数转以unit为单位的内存大小
     *
     * @param byteNum 字节数
     * @param unit    单位类型
     *                <ul>
     *                <li>{@link LibConstant.MemoryUnit#BYTE}: 字节</li>
     *                <li>{@link LibConstant.MemoryUnit#KB} : 千字节</li>
     *                <li>{@link LibConstant.MemoryUnit#MB} : 兆</li>
     *                <li>{@link LibConstant.MemoryUnit#GB} : GB</li>
     *                </ul>
     * @return 以unit为单位的size
     */
    public double byte2MemorySize(long byteNum, LibConstant.MemoryUnit unit)
    {
        if (byteNum < 0)
            return -1;
        switch (unit)
        {
            default:
            case BYTE:
                return (double) byteNum;
            case KB:
                return (double) byteNum / LibConstant.KB;
            case MB:
                return (double) byteNum / LibConstant.MB;
            case GB:
                return (double) byteNum / LibConstant.GB;
        }
    }

    /**
     * 字节数转合适内存大小
     * <p>
     * 保留3位小数
     * </p>
     *
     * @param byteNum 字节数
     * @return 合适内存大小
     */
    @SuppressLint("DefaultLocale")
    public String byte2FitMemorySize(long byteNum)
    {
        if (byteNum < 0)
        {
            return "shouldn't be less than zero!";
        } else if (byteNum < LibConstant.KB)
        {
            return String.format("%.3fB", byteNum + 0.0005);
        } else if (byteNum < LibConstant.MB)
        {
            return String.format("%.3fKB", byteNum / LibConstant.KB + 0.0005);
        } else if (byteNum < LibConstant.GB)
        {
            return String.format("%.3fMB", byteNum / LibConstant.MB + 0.0005);
        } else
        {
            return String.format("%.3fGB", byteNum / LibConstant.GB + 0.0005);
        }
    }

    /**
     * 以unit为单位的时间长度转毫秒时间戳
     *
     * @param timeSpan 毫秒时间戳
     * @param unit     单位类型
     *                 <ul>
     *                 <li>{@link LibConstant.TimeUnit#MSEC}: 毫秒</li>
     *                 <li>{@link LibConstant.TimeUnit#SEC }: 秒</li>
     *                 <li>{@link LibConstant.TimeUnit#MIN }: 分</li>
     *                 <li>{@link LibConstant.TimeUnit#HOUR}: 小时</li>
     *                 <li>{@link LibConstant.TimeUnit#DAY }: 天</li>
     *                 </ul>
     * @return 毫秒时间戳
     */
    public long timeSpan2Millis(long timeSpan, LibConstant.TimeUnit unit)
    {
        switch (unit)
        {
            default:
            case MSEC:
                return timeSpan;
            case SEC:
                return timeSpan * LibConstant.SEC;
            case MIN:
                return timeSpan * LibConstant.MIN;
            case HOUR:
                return timeSpan * LibConstant.HOUR;
            case DAY:
                return timeSpan * LibConstant.DAY;
        }
    }

    /**
     * 毫秒时间戳转以unit为单位的时间长度
     *
     * @param millis 毫秒时间戳
     * @param unit   单位类型
     *               <ul>
     *               <li>{@link LibConstant.TimeUnit#MSEC}: 毫秒</li>
     *               <li>{@link LibConstant.TimeUnit#SEC }: 秒</li>
     *               <li>{@link LibConstant.TimeUnit#MIN }: 分</li>
     *               <li>{@link LibConstant.TimeUnit#HOUR}: 小时</li>
     *               <li>{@link LibConstant.TimeUnit#DAY }: 天</li>
     *               </ul>
     * @return 以unit为单位的时间长度
     */
    public long millis2TimeSpan(long millis, LibConstant.TimeUnit unit)
    {
        switch (unit)
        {
            default:
            case MSEC:
                return millis;
            case SEC:
                return millis / LibConstant.SEC;
            case MIN:
                return millis / LibConstant.MIN;
            case HOUR:
                return millis / LibConstant.HOUR;
            case DAY:
                return millis / LibConstant.DAY;
        }
    }

    /**
     * 毫秒时间戳转合适时间长度
     *
     * @param millis    毫秒时间戳
     *                  <p>
     *                  小于等于0，返回null
     *                  </p>
     * @param precision 精度
     *                  <p>
     *                  precision = 0，返回null
     *                  </p>
     *                  <p>
     *                  precision = 1，返回天
     *                  </p>
     *                  <p>
     *                  precision = 2，返回天和小时
     *                  </p>
     *                  <p>
     *                  precision = 3，返回天、小时和分钟
     *                  </p>
     *                  <p>
     *                  precision = 4，返回天、小时、分钟和秒
     *                  </p>
     *                  <p>
     *                  precision >= 5，返回天、小时、分钟、秒和毫秒
     *                  </p>
     * @return 合适时间长度
     */
    @SuppressLint("DefaultLocale")
    public String millis2FitTimeSpan(long millis, int precision)
    {
        if (millis <= 0 || precision <= 0)
            return null;
        StringBuilder sb = new StringBuilder();
        String[] units = {"天", "小时", "分钟", "秒", "毫秒"};
        int[] unitLen = {86400000, 3600000, 60000, 1000, 1};
        precision = Math.min(precision, 5);
        for (int i = 0; i < precision; i++)
        {
            if (millis >= unitLen[i])
            {
                long mode = millis / unitLen[i];
                millis -= mode * unitLen[i];
                sb.append(mode).append(units[i]);
            }
        }
        return sb.toString();
    }

    /**
     * bytes转bits
     *
     * @param bytes 字节数组
     * @return bits
     */
    public String bytes2Bits(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes)
        {
            for (int j = 7; j >= 0; --j)
            {
                sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1');
            }
        }
        return sb.toString();
    }

    /**
     * bits转bytes
     *
     * @param bits 二进制
     * @return bytes
     */
    public byte[] bits2Bytes(String bits)
    {
        int lenMod = bits.length() % 8;
        int byteLen = bits.length() / 8;
        // 不是8的倍数前面补0
        if (lenMod != 0)
        {
            for (int i = lenMod; i < 8; i++)
            {
                bits = "0" + bits;
            }
            byteLen++;
        }
        byte[] bytes = new byte[byteLen];
        for (int i = 0; i < byteLen; ++i)
        {
            for (int j = 0; j < 8; ++j)
            {
                bytes[i] <<= 1;
                bytes[i] |= bits.charAt(i * 8 + j) - '0';
            }
        }
        return bytes;
    }

    /**
     * inputStream转outputStream
     *
     * @param is 输入流
     * @return outputStream子类
     */
    public ByteArrayOutputStream input2OutputStream(InputStream is)
    {
        if (is == null)
            return null;
        try
        {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] b = new byte[LibConstant.KB];
            int len;
            while ((len = is.read(b, 0, LibConstant.KB)) != -1)
            {
                os.write(b, 0, len);
            }
            return os;
        } catch (IOException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            CloseUtils.closeIO(is);
        }
    }

    /**
     * outputStream转inputStream
     *
     * @param out 输出流
     * @return inputStream子类
     */
    public ByteArrayInputStream output2InputStream(OutputStream out)
    {
        if (out == null)
            return null;
        return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
    }

    /**
     * inputStream转byteArr
     *
     * @param is 输入流
     * @return 字节数组
     */
    public byte[] inputStream2Bytes(InputStream is)
    {
        if (is == null)
            return null;
        return input2OutputStream(is).toByteArray();
    }

    /**
     * byteArr转inputStream
     *
     * @param bytes 字节数组
     * @return 输入流
     */
    public InputStream bytes2InputStream(byte[] bytes)
    {
        if (bytes == null || bytes.length <= 0)
            return null;
        return new ByteArrayInputStream(bytes);
    }

    /**
     * outputStream转byteArr
     *
     * @param out 输出流
     * @return 字节数组
     */
    public byte[] outputStream2Bytes(OutputStream out)
    {
        if (out == null)
            return null;
        return ((ByteArrayOutputStream) out).toByteArray();
    }

    /**
     * outputStream转byteArr
     *
     * @param bytes 字节数组
     * @return 字节数组
     */
    public OutputStream bytes2OutputStream(byte[] bytes)
    {
        if (bytes == null || bytes.length <= 0)
            return null;
        ByteArrayOutputStream os = null;
        try
        {
            os = new ByteArrayOutputStream();
            os.write(bytes);
            return os;
        } catch (IOException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            CloseUtils.closeIO(os);
        }
    }

    /**
     * inputStream转string按编码
     *
     * @param is          输入流
     * @param charsetName 编码格式
     * @return 字符串
     */
    public String inputStream2String(InputStream is, String charsetName)
    {
        if (is == null || TextUtils.isEmpty(charsetName))
            return null;
        try
        {
            return new String(inputStream2Bytes(is), charsetName);
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转inputStream按编码
     *
     * @param string      字符串
     * @param charsetName 编码格式
     * @return 输入流
     */
    public InputStream string2InputStream(String string, String charsetName)
    {
        if (string == null || TextUtils.isEmpty(charsetName))
            return null;
        try
        {
            return new ByteArrayInputStream(string.getBytes(charsetName));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * outputStream转string按编码
     *
     * @param out         输出流
     * @param charsetName 编码格式
     * @return 字符串
     */
    public String outputStream2String(OutputStream out, String charsetName)
    {
        if (out == null || TextUtils.isEmpty(charsetName))
            return null;
        try
        {
            return new String(outputStream2Bytes(out), charsetName);
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转outputStream按编码
     *
     * @param string      字符串
     * @param charsetName 编码格式
     * @return 输入流
     */
    public OutputStream string2OutputStream(String string, String charsetName)
    {
        if (string == null || TextUtils.isEmpty(charsetName))
            return null;
        try
        {
            return bytes2OutputStream(string.getBytes(charsetName));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * bitmap转byteArr
     *
     * @param bitmap bitmap对象
     * @param format 格式
     * @return 字节数组
     */
    public byte[] bitmap2Bytes(Bitmap bitmap, Bitmap.CompressFormat format)
    {
        if (bitmap == null)
            return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(format, 100, baos);
        return baos.toByteArray();
    }

    /**
     * byteArr转bitmap
     *
     * @param bytes 字节数组
     * @return bitmap
     */
    public Bitmap bytesToBitmap(byte[] bytes)
    {
        return (bytes == null || bytes.length == 0) ? null : BitmapFactory.decodeByteArray(bytes,
                0, bytes.length);
    }

    /**
     * @param inSampleSize 压缩图片1,2,4,6,8  设置为原图片的1/X，以节省内存资源
     */
    public Bitmap bytesToBitmap(byte[] bytes, int inSampleSize)
    {
        if (bytes == null || bytes.length == 0)
        {
            return null;
        }
        InputStream input;
        Bitmap bitmap;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;
        input = new ByteArrayInputStream(bytes);
        SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
                input, null, options));  //软引用
        bitmap = (Bitmap) softRef.get();
        try
        {
            if (input != null)
            {
                input.close();
            }
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 图片byte数组转为base64
     */
    public String imageBytesToBase64(byte[] bytes)
    {
        return bitmapToBase64(bytesToBitmap(bytes));
    }

    /**
     * bitmap转为base64
     */
    public String bitmapToBase64(Bitmap bitmap)
    {
        String result = null;
        ByteArrayOutputStream baos = null;
        try
        {
            if (bitmap != null)
            {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (baos != null)
                {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return result;
    }

    public Bitmap Base64ToBitmap(String base64str)
    {
        Bitmap bitmap = null;
        try
        {
            byte[] bitmapByte;
            if (base64str.contains(","))
            {
                bitmapByte = Base64.decode(base64str.split(",")[1], Base64.DEFAULT);
            } else
            {
                bitmapByte = Base64.decode(base64str, Base64.DEFAULT);
            }
            bitmap = BitmapFactory.decodeByteArray(bitmapByte, 0, bitmapByte.length);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return bitmap;
    }


    public Bitmap drawable2Bitmap(Drawable drawable)
    {
        if (drawable instanceof BitmapDrawable)
        {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable)
        {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else
        {
            return null;
        }
    }

    /**
     * bitmap转drawable
     *
     * @param res    resources对象
     * @param bitmap bitmap对象
     * @return drawable
     */
    public Drawable bitmap2Drawable(Resources res, Bitmap bitmap)
    {
        return bitmap == null ? null : new BitmapDrawable(res, bitmap);
    }

    /**
     * drawable转byteArr
     *
     * @param drawable drawable对象
     * @param format   格式
     * @return 字节数组
     */
    public byte[] drawable2Bytes(Drawable drawable, Bitmap.CompressFormat format)
    {
        return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format);
    }

    /**
     * byteArr转drawable
     *
     * @param res   resources对象
     * @param bytes 字节数组
     * @return drawable
     */
    public Drawable bytes2Drawable(Resources res, byte[] bytes)
    {
        return res == null ? null : bitmap2Drawable(res, bytesToBitmap(bytes));
    }

    /**
     * view转Bitmap
     *
     * @param view 视图
     * @return bitmap
     */
    public Bitmap view2Bitmap(View view)
    {
        if (view == null)
            return null;
        Bitmap ret = Bitmap
                .createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(ret);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
        {
            bgDrawable.draw(canvas);
        } else
        {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return ret;
    }

    public HashMap<String, String> Bean2HashMap(Object object)
    {
        HashMap<String, String> params = new HashMap<>();
        if (object == null)
        {
            return params;
        }
        Class clazz = object.getClass();
        Class<? extends Object> superclass = clazz.getSuperclass();

        Field[] fields = clazz.getDeclaredFields();
        Field[] superFields = superclass.getDeclaredFields();

        if (fields == null || fields.length == 0)
        {
            return params;
        }
        try
        {
            for (Field field : fields)
            {
                field.setAccessible(true);
                params.put(field.getName(), String.valueOf(field.get(object)));
            }
            for (Field superField : superFields)
            {
                superField.setAccessible(true);
                params.put(superField.getName(), String.valueOf(superField.get(object)));
            }
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        } catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        return params;
    }

    public String simpleFormatSize(long size)
    {
        String re;
        if (size < KB)
        {
            re = "" + size + "B";
        } else if (size < (KB * KB))
        {
            float f = ((float) size) / (KB);
            re = String.format("%.2fKB", f);
        } else
        {
            float f = ((float) size) / (KB * KB);
            re = String.format("%.2fMB", f);
        }
        return re;
    }

    public int ipStr2Int(String ip) throws UnknownHostException
    {
        try
        {
            if (ip == null)
                return 0;
            String[] parts = ip.split("\\.");
            if (parts.length != 4)
            {
                throw new UnknownHostException(ip);
            }
            int a = Integer.parseInt(parts[0]);
            int b = Integer.parseInt(parts[1]) << 8;
            int c = Integer.parseInt(parts[2]) << 16;
            int d = Integer.parseInt(parts[3]) << 24;
            return a | b | c | d;
        } catch (NumberFormatException ex)
        {
            throw new UnknownHostException(ip);
        }
    }

    public String ipInt2Str(int i)
    {
        return ((i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF));
    }

}
